package org.goodev.arch.vm;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.support.annotation.NonNull;
import android.util.Log;

import org.goodev.arch.App;
import org.goodev.arch.api.ApiResponse;
import org.goodev.arch.api.User;

import java.util.Objects;


public class UserViewModel extends AndroidViewModel {
    private static final String TAG = "UserVM";
    private final LiveData<ApiResponse<User>> mUser;
    private final MutableLiveData<String> mUserId = new MutableLiveData<>();

    public UserViewModel(Application app) {
        super(app);
        mUser = Transformations.switchMap(mUserId, id -> {
            Log.e(TAG, "UserViewModel() called with: id = [" + id + "]");
            return ((App) app).getGithubService().getUser(id);
        });

    }

    void setUser(@NonNull String id) {
        if (Objects.equals(this.mUserId.getValue(), id)) {
            return;
        }
        this.mUserId.postValue(id);
    }

    LiveData<ApiResponse<User>> getUser() {
        return mUser;
    }
}
